package com.weike.lib.xxx;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.ImageObserver;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class PrintImg extends JFrame implements Printable {
	/*
	 * 
	 * 1.Java 2 Printing Api
		对一个GUI程序来说，打印和打印预览是现在大多数程序都要实现的功能。
		在Java2之前，显然设计者们做的不太好。
		但Java2 之后大为改观。先介绍一下Java2提供的与打印有关的API.
		1.1 PrintJob    class java.awt.print.PrinterJob
		    这个类是Java2中控制打印的最主要的一个类。
		    一个典型的打印过程如下：
		    PrinterJob prnJob=PrinterJob.getPrinterJob(); //返回一个PrintJob实例
		    prnJob.setPrintable(myPrintable);  //设置PrintJob的可打印对象
		    if(!prnJob.printDialog())       //显示一个与平台有关的打印dialog.
		                   // 比如在windows里就是大家熟悉的一个
		                   // PrintDialog有OK,Cancel的button,还有设置打印范围的
		                   //文本框等。如果按了Cancel,则返回false.不打印
		       return;
		    prnJob.print();//否则，调用print方法，进行打印。

		    其中的可打印对象是一个实现了Printable 接口的对象。
		    凡是希望打印的对象都要实现此接口。
		1.2 Printable 接口.
		    abstract interface java.awt.print.Printable
		    该接口只定义了一个方法：print,
		    有三个参数：
		    Graphics graphics:类似于VC中的CDC,即设备环境，graphics context
		           注意：这个graphics 可以在 print方法中转换为Graphics2D对象。
		           就可以利用最新的2D功能
		    PageFormat pageFormat: 关于页格式的一个对象。由此对象可以得到或设置
		                  页的可打印范围，打印方向等等。
		    int pageIndex:将要打印的页的编号，由零开始。
		    print 方法的返回值有两个： PAGE_EXISTS  当本页成功打印
		                               NO_SUCH_PAGE 当index太大或不存在本页。


	 */
	private Image img;

	private JButton previewButton = null;

	private JPanel controlPanel = null;

	private JButton printButton = null;

	private Canvas canvas = null;

	private PageFormat pf;

	public PrintImg() {
		//打印图片类
		canvas = new MyCanvas();
		pf = new PageFormat();
		pf.setOrientation(PageFormat.LANDSCAPE);
		printButton = getPrintButton("开始打印");
		img = Toolkit.getDefaultToolkit().getImage(PrintImg.class.getResource("/img/zhaojie.jpg"));
		initialize();
	}

	// 界面初始化方法
	private void initialize() {
		this.setSize(new Dimension(840, 700));
		BorderLayout borderLayout = new BorderLayout();
		borderLayout.setHgap(10);
		setLayout(borderLayout);
		add(getControlPanel(), BorderLayout.SOUTH);
		add(canvas, BorderLayout.CENTER);
		this.setTitle("打印预览");
	}

	// 实现paint()方法
	public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
			throws PrinterException {
		int x = (int) pageFormat.getImageableX(); // 获取可打印区域坐标的X位置
		int y = (int) pageFormat.getImageableY(); // 获取可打印区域坐标的Y位置
		Graphics2D g2 = (Graphics2D) graphics;
		g2.drawImage(img, x, y, this); // 绘制图像
		return Printable.PAGE_EXISTS; // 返回PAGE_EXISTS
	}

	// 打印预览按钮
	private JButton getPreviewButton() {
		if (previewButton == null) {
			previewButton = new JButton();
			previewButton.setText("打印预览");
			previewButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					PrinterJob job = PrinterJob.getPrinterJob();
					pf = job.pageDialog(pf);
					canvas.repaint();
				}
			});
		}
		return previewButton;
	}

	//开始打印按钮
	private JButton getPrintButton(String str){
		printButton = new JButton(str);
		printButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				PrinterJob job = PrinterJob.getPrinterJob();
				job.setJobName("打印图片");
				job.setPrintable(new Printable() {
					@Override
					public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
						if(pageIndex > 0){
							return Printable.NO_SUCH_PAGE;//若不是从0页开始打印返回
						}
						int x = (int)pageFormat.getImageableX();
						int y = (int)pageFormat.getImageableY();//有效打印内容左上角点的坐标
						Graphics2D g2 = (Graphics2D)graphics;
						g2.translate(x, y);
						g2.drawImage(img, x, y, null);
						return Printable.PAGE_EXISTS;
					}
				});//设置打印页面
				try {
					job.print();
				} catch (PrinterException e1) {
					e1.printStackTrace();
				}
			}
		});
		return printButton;
	}

	// 控制面板
	private JPanel getControlPanel() {
		if (controlPanel == null) {
			FlowLayout flowLayout = new FlowLayout();
			flowLayout.setVgap(2);
			flowLayout.setHgap(30);
			controlPanel = new JPanel();
			controlPanel.setLayout(flowLayout);
			controlPanel.add(getPreviewButton(), null);
			controlPanel.add(printButton, null);
		}
		return controlPanel;
	}

	class MyCanvas extends Canvas {
		public void paint(Graphics g) {
			try {
				super.paint(g);
				Graphics2D g2 = (Graphics2D) g;
				g2.translate(10, 10);
				int x = (int) (pf.getImageableX() - 1);
				int y = (int) (pf.getImageableY() - 1);
				int width = (int) (pf.getImageableWidth() + 1);
				int height = (int) (pf.getImageableHeight() + 1);
				int mw=(int) pf.getWidth();
				int mh=(int) pf.getHeight();
				g2.drawRect(0, 0, mw, mh);
				g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_ROUND,	BasicStroke.JOIN_ROUND, 10f, new float[] { 5, 5 }, 0f));
				g2.drawRect(x, y, width, height);
				PrintImg.this.print(g, pf, 0);
			} catch (PrinterException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		try {
			PrintImg pp = new PrintImg();
			pp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			pp.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}